package cn.itsource.basic.config.interceptor;


import cn.itsource.basic.util.JsonResult;
import cn.itsource.basic.util.PetConstant;
import cn.itsource.basic.util.RedisService;
import cn.itsource.org.pojo.loginInfo.LoginInfo;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.stream.Location;
import java.io.IOException;
import java.io.PrintWriter;

//交给spring管理
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Resource
    private RedisService redisService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("地址:{}",request.getRequestURL());
        //获取前端请求头token
        String token = request.getHeader("token");
        //判断
        if(StringUtils.isBlank(token)){
            //设置响应头
            return LoginOutTime(response);
        }
        //获取用户信息
        LoginInfo loginInfo = redisService.getKeyObjectValue(token, LoginInfo.class);
        if(loginInfo==null){
            return LoginOutTime(response);
        }
        //刷新
        redisService.setStringKeyAndValue(token,loginInfo,30);
        return true;
    }

    private boolean LoginOutTime(HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        JsonResult jsonResult = JsonResult.createError(PetConstant.SYS_LOGIN_TIMEOUT, "请重新登录");
        PrintWriter writer = response.getWriter();
        //阿里巴巴
        writer.write(JSONObject.toJSONString(jsonResult));
        return false;
    }
}
